<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="68px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="部门归属" prop="orgId">
            <treeselect v-model="deptId" :options="deptOptions" :show-count="true" placeholder="请选择部门归属"
              :default-expand-level="4" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="顾问" prop="updateBys">
            <el-select v-model="userId" placeholder="顾问" clearable filterable >
              <el-option v-for="user in sysUsersList" :key="user.userId" :label="user.nickName" :value="user.userId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="来访时间" prop="createTime">
            <el-date-picker v-model="createTime" type="daterange" :picker-options="pickerOptions" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" align="right" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
              style="width: 100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>

    <el-table v-loading="loading"
              :data="visitRecordList"
              @selection-change="handleSelectionChange"
              show-summary
              :summary-method="getSummaries">
      <el-table-column label="部门归属" align="center" prop="deptName" />
      <el-table-column label="顾问" align="center" prop="userName" />
      <el-table-column label="来访人数" align="center" prop="visitCount" />
    </el-table>

  </div>
</template>

<script>
import { visitStaticList, getVisitRecord } from "@/api/crmsys/report/visitRecord";
import { childrenAlldeptTree } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import {
  getAllDeptandUsers
} from "@/api/crmsys/custinfo/custinfo";

export default {
  name: "VisitRecord",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 来访登记统计表格数据
      visitRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      deptId: null,
      userId: null,
      createTime: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        custId: null,
        custName: null,
        mobile: null,
        empName: null,
        empMobile: null,
      },
      // 表单参数
      form: {},
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 部门归属树选项
      deptOptions: [],
      sysUsersList: [],
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getDeptAndUsers();
  },
  methods: {
    /** 总计人数 */
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计人数';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (column.property === 'visitCount') {
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              }else {
                return prev;
              }
            }, 0);
            sums[index] += ' 人';
          } else {
            sums[index] = '---'
          }
        }
      });
      return sums;
    },
    /** 查询来访登记统计列表 */
    getList() {
      this.loading = true;

      this.addDateRange(this.queryParams, this.createTime, "createTime");
      this.queryParams.params.userId = this.userId;
      this.queryParams.params.deptId = this.deptId;
      visitStaticList(this.queryParams).then(response => {
        this.visitRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        custId: null,
        custName: null,
        mobile: null,
        empName: null,
        empMobile: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加来访登记统计";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getVisitRecord(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改来访登记统计";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateVisitRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVisitRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 查询部门归属下拉树结构 */
    getDeptTree() {
      var dept = { deptId: this.$store.state.user.deptid }
      childrenAlldeptTree(dept).then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 获取部门归属和人员信息 */
    getDeptAndUsers() {
      getAllDeptandUsers().then((response) => {
        this.sysUsersList = response.data.sysUsersList;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('crmsys/visitRecord/export', {
        ...this.queryParams
      }, `visitRecord_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
@import '@/assets/styles/command.scss';
</style>
